package com.joysuch.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.util.DateUtils;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import com.joysuch.entity.*;
import com.joysuch.enums.AllotKind;
import com.joysuch.enums.HourTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;

import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.*;

@Slf4j
public class ExcelHandle2 {
    /**
     * 处理报表
     *
     * @param path         需要处理的Excel路径
     * @param templeteFile 模板文件
     */
    public static void handle(File path, InputStream templeteFile) {
        log.info("使用ExcelHandle2处理-{}", LocalDateTime.now());
        List<Salary> inputList1 = ExcelUtil.readExcel(path, Salary.class, "输入1 工资表", 1);
        List<TimesSheet> inputList2 = ExcelUtil.readExcel(path, TimesSheet.class, "输入2 工时表", 3);
        List<MidA> midListA = ExcelUtil.readExcel(path, MidA.class, "中间表-研发工时分配A", 1);

        // 获取配置，用作后面计算比例
        Map<String, Set<String>> conf = getConf();
        Set<String> rdDeptSet = conf.get("rdDept");
        Set<String> unRdDeptSet = conf.get("unRdDept");
        // *****************************一级部门和BU的映射，正式操作一级部门和Bu会一致，此项需更改****************************************************************
        Set<String> deptOneBuSet = conf.get("deptOneBu");
        Map<String, String> deptOneBuMapping = getDeptOneBuMapping(deptOneBuSet);
//        Map<String, String> deptOneBuMapping = getBu();
        // *********************************************************************************************
        Map<String, BigDecimal> allHourMap = getProportionHor(inputList2, rdDeptSet);
        // 建表
        JdbcH2Util.createTable(MidA.class);
        // 插入数据
        log.info("添加原始数据开始-{}", LocalDateTime.now());
        for (MidA midA : midListA) {

//            if ((!deptOneBuMapping.isEmpty() && !Objects.equals(deptOneBuMapping.get(midA.getDeptOne()), midA.getBu())) || !Objects.equals(midA.getDeptOne(), midA.getBu())) {
//                midA.setAllotFlag(HourTypeEnum.转嫁.getAllotType());
//            }

            if (deptOneBuMapping.isEmpty()) {
                if (!Objects.equals(midA.getDeptOne(), midA.getBu())) {
                    // 一级部门和BU不一致，为转嫁
                    midA.setAllotFlag(HourTypeEnum.转嫁.getAllotType());
                }
            } else {
                if (!Objects.equals(deptOneBuMapping.get(midA.getDeptOne()), midA.getBu())) {
                    // 一级部门和BU不一致，为转嫁
                    midA.setAllotFlag(HourTypeEnum.转嫁.getAllotType());
                }
            }

////            if (!Objects.equals(midA.getDeptOne(), midA.getBu())) {
//            if (!Objects.equals(deptOneBuMapping.get(midA.getDeptOne()), midA.getBu())) {
//                // 一级部门和BU不一致，为转嫁
//                midA.setAllotFlag(HourTypeEnum.转嫁.getAllotType());
//            }
            JdbcH2Util.insert(midA, MidA.class);
//            JdbcUtilTemp.insert(midA, MidA.class);
        }
        log.info("添加原始数据结束-{}", LocalDateTime.now());
//        JdbcUtilTemp.batchSave(midListA, MidA.class, "mida");

        String type = "部门";
        log.info("分配开始-{}", LocalDateTime.now());
        Map<String, List<MidA>> allotRet = allotByType(type, inputList1, allHourMap, conf);
        log.info("分配结束-{}", LocalDateTime.now());
        List<MidA> out1Use = allotRet.get("out1Use");
        List<MidA> out2Use = allotRet.get("out2Use");

        JdbcH2Util.createTable(MidA.class, "mida2");
        JdbcH2Util.createTable(MidA.class, "mida3");
        log.info("添加分配后数据开始-{}", LocalDateTime.now());
        for (MidA midA : out1Use) {
            midA.setId(null);
            if (Objects.isNull(midA.getHourType())) {
                midA.setHourType(HourTypeEnum.原始.getAllotType());
            }

            JdbcH2Util.insert(midA, MidA.class, "mida2");
//            JdbcUtilTemp.insert(midA, MidA.class, "mida2");
        }
        for (MidA midA : out2Use) {
            midA.setId(null);
            if (Objects.isNull(midA.getHourType2())) {
                midA.setHourType2(HourTypeEnum.原始.getAllotType());
            }
            JdbcH2Util.insert(midA, MidA.class, "mida3");
//            JdbcUtilTemp.insert(midA, MidA.class, "mida3");
        }
        log.info("添加分配后数据结束-{}", LocalDateTime.now());
//        JdbcUtilTemp.batchSave(out1Use, MidA.class, "mida2");
//        JdbcUtilTemp.batchSave(out2Use, MidA.class, "mida3");

        // 查询输出一
        String selectOut1Sql = "SELECT org, deptOne, deptTwo, bu, rdNo, proName, hourType, sum(personalHour) personalHour, sum(proBonus) proBonus, sum(basicSalary) basicSalary, sum(checkDeduct) checkDeduct, sum(otherDeduct) otherDeduct, sum(currentIncome) currentIncome, sum(personalSocialSecurity) personalSocialSecurity, sum(personalProvideAged) personalProvideAged, sum(personalMedical) personalMedical, sum(personalUnemployment) personalUnemployment, sum(personalAccuFunds) personalAccuFunds, sum(companySocialSecurity) companySocialSecurity, sum(conpanyProvideAged) conpanyProvideAged, sum(conpanyMedical) conpanyMedical, sum(conpanyUnemployment) conpanyUnemployment, sum(companyInjury) companyInjury, sum(companyBear) companyBear, sum(companyHeat) companyHeat, sum(companyDisableSecurity) companyDisableSecurity, sum(lateFees) lateFees, sum(companyAccuFunds) companyAccuFunds, sum(bjAccuFunds) bjAccuFunds, sum(incomeCompany) incomeCompany, sum(corporatePart) corporatePart, sum(bonus) bonus, sum(otherCheckDeduction) otherCheckDeduction from mida2 group by org, deptOne, deptTwo, bu, rdNo, hourType order by org, deptOne, deptTwo, bu, rdNo, hourType";
        List<Out1> out1 = JdbcH2Util.query(Out1.class, selectOut1Sql);

        // 查询输出二
        String selectOut2Sql = "SELECT * FROM (\n" +
                "SELECT deptOne, deptTwo, army, bu, rdNo, proName, sum(personalHour) personalHour, (sum(basicSalary) - sum(checkDeduct) - sum(otherDeduct) + sum(corporatePart) + sum(bjAccuFunds)) salary, sum(proBonus) proBonus, sum(bonus) preYearEndBonus, '0.0' total from mida3 WHERE hourType2 = '原始' group by deptOne, deptTwo, army, bu, rdNo, proName \n" +
                "\n" +
                "UNION\n" +
                "\n" +
                "SELECT deptOne, deptTwo, army, bu, '比对' rdNo, proName, sum(personalHour) personalHour, (sum(basicSalary) - sum(checkDeduct) - sum(otherDeduct) + sum(corporatePart) + sum(bjAccuFunds)) salary, sum(proBonus) proBonus, sum(bonus) preYearEndBonus, '0.0' total from mida3 WHERE hourType2 = '分配' group by deptOne, deptTwo, army, bu, rdNo, proName \n" +
                ") t  GROUP BY deptOne, deptTwo, army, bu, rdNo, proName ";
        List<Out2> out2 = JdbcH2Util.query(Out2.class, selectOut2Sql);
        out2.forEach(out -> out.setTotal(out.getPreYearEndBonus().add(out.getProBonus()).add(out.getSalary())));

        // 查询输出三
        String selectOut3Sql = "SELECT mid.rdNo, mid.bu, mid.proName, sum(mid.personalHour) hourTotal, ifnull(sum(mid1.personalHour), '0') nxHour, ifnull(sum(mid1.incomeCompany), '0') nxIncomeCompany, ifnull(sum(mid1.bonus), '0') nxYearEndBonus, ifnull(sum(mid2.personalHour), '0') hourCheckHigh, IFNULL(sum(mid2.incomeCompany),'0') allotIncomeCompany, IFNULL(sum(mid2.bonus),'0') allotYearEndBonus from mida3 mid left join mida3 mid1 ON mid1.id = mid.id AND mid1.hourType2 = '原始' left join mida3 mid2 ON mid2.id = mid.id AND mid2.hourType2 = '分配' group by mid.rdNo, mid.bu, mid.proName order by mid.rdNo, mid.bu, mid.proName";
        List<Out3> out3 = JdbcH2Util.query(Out3.class, selectOut3Sql);
        out3.forEach(out -> out.setTotal(out.getNxIncomeCompany().add(out.getNxYearEndBonus()).add(out.getAllotIncomeCompany()).add(out.getAllotYearEndBonus())));

        // 查询输出四
        String selectOut4Sql = "SELECT bu, rdNo, proName, deptOne, deptTwo, sum(basicSalary) basicSalary, sum(proBonus) proBonus, sum(bonus) bonus, (sum(currentIncome) + sum(companySocialSecurity) + sum(companyAccuFunds)) incomeCSecurity, sum(corporatePart) corporatePart, sum(bjAccuFunds) accuFunds, sum(otherCheckDeduction) checkOtherDeduct FROM mida where allotFlag = '转嫁' GROUP BY bu, rdNo, proName, deptOne, deptTwo ORDER BY bu, rdNo, proName, deptOne, deptTwo";
        List<Out4> out4 = JdbcH2Util.query(Out4.class, selectOut4Sql);
        out4.forEach(out -> out.setTotal(out.getBasicSalary().add(out.getProBonus()).add(out.getBonus()).add(out.getCorporatePart()).add(out.getAccuFunds()).subtract(out.getCheckOtherDeduct())));

        String yyyyMMddHHmmss = DateUtils.format(new Date(), "yyyyMMdd_HHmmss");

        // ***************************打包exe时删除，改成下面的***********************************************************************
        // 输出路径
        String outPath = "C:/ExcelHandle";
        String excelName = "/" + yyyyMMddHHmmss + "报表处理.xlsx";
        String fileAllName = outPath + excelName;
        File outputFolder = new File(outPath);
        if (!outputFolder.exists()) {
            outputFolder.mkdirs();// 如果文件夹不存在，则创建
        }
        // **************************************************************************************************

        // **************************************************************************************************
        // 打包exe文件后使用的路径
//        String outPath = "out/";
//        String excelName = "/" + yyyyMMddHHmmss + "报表处理.xlsx";
//        String fileAllName = outPath + excelName;
//        File outputFolder = new File(outPath);
//        if (!outputFolder.exists()) {
//            outputFolder.mkdirs();// 如果文件夹不存在，则创建
//        }
        // **************************************************************************************************
        log.info("Excel处理开始-{}", LocalDateTime.now());
        try (ExcelWriter excelWriter = EasyExcel.write(fileAllName).withTemplate(templeteFile).build()) {
//            WriteSheet allotA = EasyExcel.writerSheet().sheetNo(2).build();
            WriteSheet outSheet1 = EasyExcel.writerSheet().sheetNo(0).build();
            WriteSheet outSheet2 = EasyExcel.writerSheet().sheetNo(1).build();
            WriteSheet outSheet3 = EasyExcel.writerSheet().sheetNo(2).build();
            WriteSheet outSheet4 = EasyExcel.writerSheet().sheetNo(3).build();
//            WriteSheet allotA2 = EasyExcel.writerSheet().sheetNo(8).build();

//            excelWriter.fill(new FillWrapper("data", allotList), allotA);
//            excelWriter.fill(new FillWrapper("data", allotList2), allotA2);
            excelWriter.fill(new FillWrapper("data", out1), outSheet1);
            excelWriter.fill(new FillWrapper("data", out2), outSheet2);
            excelWriter.fill(new FillWrapper("data", out3), outSheet3);
            excelWriter.fill(new FillWrapper("data", out4), outSheet4);
            excelWriter.finish();
            log.info("Excel处理完成-{}", LocalDateTime.now());
        } finally {
            if (templeteFile != null) {
                try {
                    templeteFile.close(); // 关闭输入流
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        JdbcH2Util.closeConnection();

    }

    private static Map<String, List<MidA>> allotByType(String type, List<Salary> inputList1, Map<String, BigDecimal> allHourMap, Map<String, Set<String>> conf) {
//        Map<String, Set<String>> conf = getConf();
        Set<String> leaderSet = conf.get("leader");
        Set<String> assistantSet = conf.get("assistant");
        Set<String> rdDeptSet = conf.get("rdDept");
        Set<String> unRdDeptSet = conf.get("unRdDept");


        List<MidA> allList = new ArrayList<>();
        List<MidA> allList2 = new ArrayList<>();
        String allotCompareSql = "SELECT org, deptOne, deptTwo, `name`, sum(personalHour) total FROM mida WHERE allotScreen = '比对-分配' GROUP BY org, deptOne, deptTwo, `NAME`"; // ++++++++++++++++++++++++++++++++++++++
//        String allotCompareSql = "SELECT deptTwo, `name`, sum(personalHour) total FROM mida WHERE allotScreen = '比对-分配' GROUP BY deptTwo, `NAME`";
        String allotOtherSql = "SELECT org, deptOne, deptTwo, `name`, sum(personalHour) total FROM mida WHERE allotScreen = '其他-分配' GROUP BY org, deptOne, deptTwo, `NAME`"; // ++++++++++++++++++++++++++++++++++++++
//        String allotOtherSql = "SELECT deptTwo, `name`, sum(personalHour) total FROM mida WHERE allotScreen = '其他-分配' GROUP BY deptTwo, `NAME`";
//        String allotCompareSql = "SELECT org, deptOne, deptTwo, `name`, sum(personalHour) total FROM mida WHERE allotScreen = '比对-分配' GROUP BY org, deptOne, deptTwo, `NAME`";
        List<GroupType> allotCompareList = JdbcH2Util.query(GroupType.class, allotCompareSql);
        List<GroupType> allotOtherList = JdbcH2Util.query(GroupType.class, allotOtherSql);
        Map<String, BigDecimal> allotCompareMap = new HashMap<>();
        Map<String, BigDecimal> allotOtherMap = new HashMap<>();
        for (GroupType groupType : allotCompareList) {
            allotCompareMap.put(groupType.getName(), groupType.getTotal());
        }
        for (GroupType groupType : allotOtherList) {
            allotOtherMap.put(groupType.getName(), groupType.getTotal());
        }

        String groupTypeSql = "SELECT org, deptOne, deptTwo FROM mida GROUP BY org, deptOne, deptTwo"; // ++++++++++++++++++++++++++++++++++++++
//        String groupTypeSql = "SELECT deptTwo FROM mida GROUP BY deptTwo";
        List<GroupType> groupTypeList = JdbcH2Util.query(GroupType.class, groupTypeSql);
        Map<String, List<MidA>> getWaitAllotMap = new HashMap<>();
        for (GroupType groupType : groupTypeList) {
            String org = groupType.getOrg();
            String deptOne = groupType.getDeptOne();
            String deptTwo = groupType.getDeptTwo();
            String key = getODDKey(groupType);
            String getDeptTwoSql = "select * from mida where org = '" + org + "' and deptOne = '" + deptOne + "' and deptTwo = '" + deptTwo + "' and (rdNo like 'RD%' and rdNo not like 'RDT%' or rdNo like 'CD%') and allotFlag IS NULL order by personalHour";// ++++++++++++++++++++++++++++++++++++++
//            String getDeptTwoSql = "select * from mida where deptTwo = '" + deptTwo + "' and (rdNo like 'RD%' and rdNo not like 'RDT%' or rdNo like 'CD%') order by personalHour";
            List<MidA> queryList = JdbcH2Util.query(MidA.class, getDeptTwoSql);
            getWaitAllotMap.put(key, queryList);
        }
        Map<String, List<MidA>> result = new HashMap<>();
        List<MidA> allotList = new ArrayList<>();
        List<MidA> allotList2 = new ArrayList<>();
        for (Salary salary : inputList1) {
            List<MidA> personalList = new ArrayList<>();
            String org = salary.getOrg();
            String deptOne = salary.getDeptOne();
            String deptTwo = salary.getDeptTwo();
            String name = salary.getName();
            if ("L".equals(name)) {
                System.out.println("hello");
            }
            // 公司-一级部门-二级部门
            String oddKey = getODDKey(salary);
            // 等待分配的
            List<MidA> waits;
            // 如果是领导或者助理，只按照一级部门（忽略公司）分配
            if (leaderSet.contains(name) || assistantSet.contains(name)) {
                String getDeptTwoSql = "select * from mida where deptOne = '" + deptOne + "' and (rdNo like 'RD%' and rdNo not like 'RDT%' or rdNo like 'CD%') and allotFlag IS NULL order by personalHour";
                waits = JdbcH2Util.query(MidA.class, getDeptTwoSql);
            } else {
                waits = getWaitAllotMap.get(oddKey);
            }
            // 这个人的“其他-分配”工时
            BigDecimal personalOtherHour = allotOtherMap.get(name);
            // 这个人的“比对-分配”工时

            BigDecimal personalCompareHour = allotCompareMap.get(name);
            List<MidA> allotedOtherList = newAllot(waits, salary, personalOtherHour, name, AllotKind.白色分配.getKind());
            List<MidA> allotedCompareList = newAllot(waits, salary, personalCompareHour, name, AllotKind.灰色分配.getKind());
            List<MidA> allotedCompareList2 = newAllot(waits, salary, personalCompareHour, name, AllotKind.灰色分配.getKind());

//            String getRdProSql = "select * from mida where name = '" + name + "' and (rdNo like 'RD%' and rdNo not like 'RDT%') or rdNo like 'CD%' order by personalHour";
            String getRdProSql = "select * from mida where name = '" + name + "' AND allotScreen not like '%分配%' order by personalHour";
            List<MidA> rdProList = JdbcH2Util.query(MidA.class, getRdProSql);

            personalList.addAll(rdProList);
            personalList.addAll(allotedOtherList);
            personalList.addAll(allotedCompareList);

            List<MidA> personalList2 = new ArrayList<>(allotedCompareList);
            String notAllotSql = "select * from mida where `name` = '" + name + "' and allotScreen <> '比对-分配'";
            List<MidA> notAllotList = JdbcH2Util.query(MidA.class, notAllotSql);
            personalList2.addAll(notAllotList);
            // 分配管理的数据
            if (leaderSet.contains(name)) {
                String allotManageSql = "SELECT * FROM mida WHERE `name` = '" + name + "' and allotScreen = '比对-分配管理'";
                List<MidA> allotManageList = JdbcH2Util.query(MidA.class, allotManageSql);
                personalList.addAll(allotManageList);
            }

            // 查询每个人的总工时
            BigDecimal sum = allHourMap.get(name);
            // 计算详情
            calcAll(personalList, salary, sum, rdDeptSet);
            calcAll(personalList2, salary, sum, rdDeptSet);

            allList.addAll(personalList);
            allList2.addAll(personalList2);
        }
        result.put("out1Use", allList);
        result.put("out2Use", allList2);
        return result;
    }

    private static List<MidA> newAllot(List<MidA> list, Salary salary, BigDecimal allot, String name, String kind) {
        // 分配种类（白色分配？灰色分配？）
        String hourType = HourTypeEnum.分配.getAllotType();
        String hourType2 = null;
        if (Objects.equals(kind, AllotKind.灰色分配.getKind())) {
            hourType2 = HourTypeEnum.分配.getAllotType();
        }
        if ("G".equals(name)) {
            System.out.println("newAllot");
        }
        List<MidA> retList = new ArrayList<>();

        if (Objects.isNull(allot) || Objects.equals(allot, BigDecimal.ZERO) || CollectionUtils.isEmpty(list)) {
            return retList;
        }
        BigDecimal sum = list.stream()
                .map(MidA::getPersonalHour)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        // 计算比例
        BigDecimal proportionTemp = new BigDecimal(1);
        BigDecimal allotTemp = allot;
        int size = list.size();
        for (MidA midA : list) {
            try {
                MidA midATemp = (MidA) midA.clone();
                midATemp.setName(name);
                midATemp.setHourType2(hourType2);
                midATemp.setHourType(hourType);
                BigDecimal proportion;
                BigDecimal personalHour;
                if (size == 1) {
                    proportion = proportionTemp;
                    personalHour = allotTemp;
                } else {
                    proportion = midA.getPersonalHour().divide(sum, 2, RoundingMode.HALF_UP);
                    personalHour = allot.multiply(proportion);
                }
                midATemp.setProportion(proportion);
                midATemp.setPersonalHour(personalHour);

                midATemp.calcAll(salary);
                midATemp.setHourType(HourTypeEnum.分配.getAllotType());
                midATemp.setHourType2(HourTypeEnum.分配.getAllotType());
                midATemp.setAddFlag(HourTypeEnum.分配.getAllotType());
                retList.add(midATemp);
                size--;
                allotTemp = allotTemp.subtract(personalHour);
                proportionTemp = proportionTemp.subtract(proportion);
            } catch (CloneNotSupportedException e) {
                throw new RuntimeException(e);
            }
        }
        return retList;
    }

    private static String getODDKey(MidA midA) {
        return midA.getOrg() + "-" + midA.getDeptOne() + "-" + midA.getDeptTwo(); // ++++++++++++++++++++++++++++++++++++++
    }

    private static String getODDKey(GroupType groupType) {
        return groupType.getOrg() + "-" + groupType.getDeptOne() + "-" + groupType.getDeptTwo(); // ++++++++++++++++++++++++++++++++++++++
    }

    private static String getODDKey(Salary salary) {
        return salary.getOrg() + "-" + salary.getDeptOne() + "-" + salary.getDeptTwo(); // ++++++++++++++++++++++++++++++++++++++
    }

    private static boolean isRD(String rdNo) {
        boolean result = false;
        if (Objects.nonNull(rdNo)) {
            if (Objects.equals("RD", rdNo.substring(0, 2)) && Objects.equals("RDT", rdNo.substring(0, 3))) {
                result = true;
            }
        }
        return result;
    }

    private static Map<String, BigDecimal> getProportionHor(List<TimesSheet> list, Set<String> rdDeptSet) {
        Map<String, BigDecimal> map = new HashMap<>();

        for (TimesSheet timesSheet : list) {
            BigDecimal personalHour;
            String deptOne = timesSheet.getDeptOne();
            String name = timesSheet.getName();
            if ("A".equals(name)) {
                System.out.println("a");
            }
            // 记录总工时
            BigDecimal recordTime = timesSheet.getRecordTime();
            // 考勤工时
            BigDecimal checkTime = timesSheet.getCheckTime();
            // 是研发部门
            if (rdDeptSet.contains(deptOne)) {
                personalHour = recordTime.compareTo(checkTime) > 0 ? recordTime : checkTime;
            } else {
                personalHour = recordTime;
            }
            map.put(name, personalHour);
        }
        return map;

    }

    /**
     * 获取领导，助理，研发部门，非研发部门
     *
     * @return
     */
    private static Map<String, Set<String>> getConf() {
        Map<String, Set<String>> ret = new HashMap<>();
        String path;
        // 获取当前 Java 程序运行的目录
        String currentDir = System.getProperty("user.dir");
        // 获取当前目录下的文件列表
        File directory = new File(currentDir);
        String absolutePath = directory.getAbsolutePath();
        // 打包exe用下面的
//        path =  absolutePath + "/conf/config.properties";
        path = "C:\\Users\\20255\\Desktop\\报表\\conf\\config.properties";
        Properties properties = new Properties();
        BufferedReader fileInputStream = null;
        try {
            fileInputStream = new BufferedReader(new InputStreamReader(Files.newInputStream(Paths.get(path)), StandardCharsets.UTF_8));
            properties.load(fileInputStream);
        } catch (IOException e) {
            log.error("读取配置文件失败, 请检查config.properties位置", e);
            throw new RuntimeException(e);
        }
        Set<String> leaderSet = getByProperty(properties.getProperty("leader"));
        Set<String> assistantSet = getByProperty(properties.getProperty("assistant"));
        Set<String> rdDeptSet = getByProperty(properties.getProperty("rdDept"));
        Set<String> unRdDeptSet = getByProperty(properties.getProperty("unRdDept"));
        Set<String> deptOneBuSet = getByProperty(properties.getProperty("deptOne-bu"));

        ret.put("leader", leaderSet);
        ret.put("assistant", assistantSet);
        ret.put("rdDept", rdDeptSet);
        ret.put("unRdDept", unRdDeptSet);
        ret.put("deptOneBu", deptOneBuSet);
        return ret;
    }

    private static Set<String> getByProperty(String str) {
        Set<String> set = new HashSet<>();
        if (str == null || str.isEmpty()) {
            return set;
        }
        String[] split = str.replace(" ", "").split(",");
        return new HashSet<>(Arrays.asList(split));
    }

    /**
     * 计算工资结果（以某人为维度的）
     *
     * @param list      这个人的所有项目
     * @param salary    工资表数据
     * @param sum       总工时
     * @param rdDeptSet 研发部门
     * @return 计算结果
     */
    private static List<MidA> calcAll(List<MidA> list, Salary salary, BigDecimal sum, Set<String> rdDeptSet) {
//        BigDecimal sum = getSum(list);

        BigDecimal proportionTemp = new BigDecimal(1);
        int size = list.size();
        BigDecimal proportion;
        BigDecimal temp = new BigDecimal(0);
        for (MidA midA : list) {
            // 如果就剩一个项目，把剩下的比例都给这个项目
            // 只适用于研发部门
            if (size == 1 && rdDeptSet.contains(midA.getDeptOne())) {
                proportion = proportionTemp;
            } else {
                proportion = midA.getPersonalHour().divide(sum, 12, RoundingMode.HALF_UP);
            }
            temp = temp.add(proportion);
            midA.setProportion(proportion);
            midA.calcAll(salary);

            proportionTemp = proportionTemp.subtract(proportion);
            size--;
        }
        return list;
    }

    private static Map<String, String> getDeptOneBuMapping(Set<String> set) {
        Map<String, String> map = new HashMap<>();
        for (String s : set) {
            String[] arr = s.split(":");
            if (arr.length == 2) {
                map.put(arr[0], arr[1]);
            }
        }
        return map;
    }

    private static BigDecimal getSum(List<MidA> list) {
        BigDecimal sum = list.stream()
                .map(MidA::getPersonalHour)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        return sum;
    }

//    /**
//     * 获取领导，助理，研发部门，非研发部门
//     *
//     * @return
//     */
//    private static Map<String, Set<String>> getConf() {
//        Map<String, Set<String>> ret = new HashMap<>();
//        // 领导
//        Set<String> leaderSet = new HashSet<>();
//        // 助理
//        Set<String> assistantSet = new HashSet<>();
//        // 研发部门
//        Set<String> rdDeptSet = new HashSet<>();
//        // 非研发部门
//        Set<String> unRdDeptSet = new HashSet<>();
//        // 通过文件获取所有研发部门
//        String path;
//        // 获取当前 Java 程序运行的目录
//        String currentDir = System.getProperty("user.dir");
//        // 获取当前目录下的文件列表
//        File directory = new File(currentDir);
//        String absolutePath = directory.getAbsolutePath();
////        path =  absolutePath + "/conf/settings.xlsx";
//        path = "C:\\Users\\20255\\Desktop\\报表\\conf\\settings.xlsx";
//        try (ExcelReader excelReader = EasyExcel.read(path).build()) {
//            ExcelListener<ExcelData> listener = new ExcelListener<>();
//            ReadSheet readSheet = EasyExcel.readSheet(0).head(ExcelData.class).registerReadListener(listener).headRowNumber(1).build();
//            excelReader.read(readSheet);
//            List<ExcelData> datas = listener.getDatas();
//            for (ExcelData data : datas) {
//                if (data.getLeader() != null) {
//                    leaderSet.add(data.getLeader());
//                }
//                if (data.getAssistant() != null) {
//                    assistantSet.add(data.getAssistant());
//                }
//                if (data.getRdDept() != null) {
//                    rdDeptSet.add(data.getRdDept());
//                }
//                if (data.getUnRdDept() != null) {
//                    unRdDeptSet.add(data.getUnRdDept());
//                }
//            }
//        }
//        ret.put("leader", leaderSet);
//        ret.put("assistant", assistantSet);
//        ret.put("rdDept", rdDeptSet);
//        ret.put("unRdDept", unRdDeptSet);
//        return ret;
//    }

    // *****************************************************************************************************************
    private static Set<String> setRDNo(List<MidA> list) {
        Set<String> set = new HashSet<>();
        for (MidA midA : list) {
            set.add(midA.getRdNo());
        }
        return set;
    }

    /**
     * 获取转嫁数据
     *
     * @param list
     * @return
     */
    private static List<MidA> getZJ(List<MidA> list) {
        List<MidA> retList = new ArrayList<>();
        for (MidA midA : list) {
            if (!Objects.equals(midA.getDeptOne(), midA.getBu())) {
                retList.add(midA);
            }
        }
        return retList;
    }

    // *****************************************************************************************************************
}
